const BaseService = require('./base_service.js');
const StoreModel = require('../model/store_model.js');

class StoreManagementService extends BaseService {

  /**
   * 添加门店
   */
  async addStore(input) {
    const db = uniCloud.database();
    const collection = db.collection(StoreModel.CL);

    // 检查门店名称是否重复
    const existingStore = await collection.where({
      name: input.name
    }).get();

    if (existingStore.data.length > 0) {
      throw new Error('门店名称已存在');
    }

    // 创建门店数据
    const storeData = {
      name: input.name,
      address: input.address,
      longitude: input.longitude,
      latitude: input.latitude,
      phone: input.phone,
      openingHours: input.openingHours || '09:00-22:00',
      coverImage: input.coverImage || '',
      services: input.services || [],
      status: 1, // 默认营业中
      createTime: Date.now(),
      updateTime: Date.now()
    };

    const result = await collection.add(storeData);
    
    return {
      storeId: result.id,
      message: '门店添加成功'
    };
  }

  /**
   * 删除门店
   */
  async deleteStore(storeId) {
    const db = uniCloud.database();
    const collection = db.collection(StoreModel.CL);

    // 检查门店是否存在
    const store = await collection.doc(storeId).get();
    if (!store.data.length) {
      throw new Error('门店不存在');
    }

    // 检查门店是否有关联数据
    // 这里可以添加检查预约、设备等关联数据的逻辑

    // 软删除
    await collection.doc(storeId).update({
      status: 0,
      updateTime: Date.now()
    });

    return { message: '门店删除成功' };
  }

  /**
   * 更新门店
   */
  async updateStore(storeId, input) {
    const db = uniCloud.database();
    const collection = db.collection(StoreModel.CL);

    // 检查门店是否存在
    const store = await collection.doc(storeId).get();
    if (!store.data.length) {
      throw new Error('门店不存在');
    }

    // 更新门店数据
    const updateData = {
      ...input,
      updateTime: Date.now()
    };

    await collection.doc(storeId).update(updateData);

    return { message: '门店更新成功' };
  }

  /**
   * 获取门店列表
   */
  async getStoreList(input) {
    const db = uniCloud.database();
    const collection = db.collection(StoreModel.CL);

    // 构建查询条件
    let whereCondition = {};
    
    if (input.status !== undefined) {
      whereCondition.status = input.status;
    }
    
    if (input.search) {
      whereCondition.name = new RegExp(input.search, 'i');
    }

    // 分页查询
    const result = await collection
      .where(whereCondition)
      .orderBy('createTime', 'desc')
      .skip((input.page - 1) * input.size)
      .limit(input.size)
      .get();

    // 获取总数
    const countResult = await collection.where(whereCondition).count();

    return {
      list: result.data,
      total: countResult.total,
      page: input.page,
      size: input.size
    };
  }
}

module.exports = StoreManagementService;
